package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.repository.FoodRepository;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class FoodService {

    private final FoodRepository foodRepository;

    public FoodService(FoodRepository foodRepository) {
        this.foodRepository = foodRepository;
    }

    // 根据ID查询商品
    @Transactional(readOnly = true)
    public HttpResult<Food> getFoodById(Long id) {
        Optional<Food> food = foodRepository.findById(id);
        return food.map(HttpResult::success)
                .orElseGet(() -> HttpResult.failure(ResultCodeEnum.NOT_FOUND));
    }

    // 查询所有商品（从HEAD版本补充）
    @Transactional(readOnly = true)
    public HttpResult<List<Food>> getAllFoods() {
        return HttpResult.success(foodRepository.findAll());
    }

    // 根据商家查询商品
    @Transactional(readOnly = true)
    public HttpResult<List<Food>> getFoodsByBusiness(Business business) {
        return HttpResult.success(foodRepository.findByBusiness(business));
    }

    // 根据商家ID查询商品（从HEAD版本补充）
    @Transactional(readOnly = true)
    public HttpResult<List<Food>> getFoodsByBusinessId(Long businessId) {
        return HttpResult.success(foodRepository.findByBusinessId(businessId));
    }

    // 添加商品
    @Transactional
    public HttpResult<Food> addFood(Food food) {
        Food saved = foodRepository.save(food);
        return HttpResult.success(saved);
    }

    // 更新商品
    @Transactional
    public HttpResult<Food> updateFood(Long id, Food food) {
        return foodRepository.findById(id)
                .map(existing -> {
                    // 更新字段
                    existing.setFoodName(food.getFoodName());
                    existing.setFoodExplain(food.getFoodExplain());
                    existing.setFoodImg(food.getFoodImg());
                    existing.setFoodPrice(food.getFoodPrice());
                    existing.setBusiness(food.getBusiness());
                    existing.setRemarks(food.getRemarks());
                    return HttpResult.success(foodRepository.save(existing));
                })
                .orElseGet(() -> HttpResult.failure(ResultCodeEnum.NOT_FOUND));
    }

    // 删除商品（从HEAD版本补充）
    @Transactional
    public HttpResult<Void> deleteFood(Long id) {
        if (foodRepository.existsById(id)) {
            foodRepository.deleteById(id);
            return HttpResult.success();
        }
        return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
    }
}